/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


/**
 * CyclicBarrier底层是基于ReentrantLock和AQS来实现
 * CyclicBarrier没有显示继承哪个父类或者实现哪个父接口, 所有AQS和重入锁不是通过继承实现的，而是通过组合实现的。
 */
public class CyclicBarrier {


    /**
     * CyclicBarrier类存在一个内部类Generation
     * 每一次使用的CycBarrier可以当成Generation的实例，其源代码如下
     */
    private static class Generation {
        boolean broken = false;  //用来表示当前屏障是否被损坏
    }

    // 可重入锁
    private final ReentrantLock lock = new ReentrantLock();
    // 条件队列
    private final Condition trip = lock.newCondition();
    // 参与的线程数量
    private final int parties;
    // 由最后一个进入 barrier 的线程执行的操作
    private final Runnable barrierCommand;
    // 当前代
    private Generation generation = new Generation();
    // 正在等待进入屏障的线程数量
    private int count;


    /**
     * 构造函数，该构造函数仅仅执行了关联该CyclicBarrier的线程数量，没有设置执行动作
     */
    public CyclicBarrier(int parties) {
        this(parties, null);
    }

    public CyclicBarrier(int parties, Runnable barrierAction) {
        // 参与的线程数量小于等于0，抛出异常
        if (parties <= 0) throw new IllegalArgumentException();
        // 设置parties
        this.parties = parties;
        // 设置count
        this.count = parties;
        // 设置barrierCommand
        this.barrierCommand = barrierAction;
    }



    /**
     * 线程在屏障处等待，直到满足条件或发生异常
     * @param timed 是否使用定时等待
     * @param nanos 如果使用定时等待，指定等待的纳秒数
     * @return 线程到达屏障时的索引
     * @throws InterruptedException 如果线程被中断
     * @throws BrokenBarrierException 如果屏障被破坏
     * @throws TimeoutException 如果使用定时等待且达到指定时间但屏障条件仍未满足
     */
    private int dowait(boolean timed, long nanos)
            throws InterruptedException, BrokenBarrierException, TimeoutException {

        // 获取锁对象
        final ReentrantLock lock = this.lock;
        // 加锁，确保线程安全
        lock.lock();
        try {
            // 获取当前代
            final Generation g = generation;

            // 如果屏障被破坏，抛出异常
            if (g.broken)
                throw new BrokenBarrierException();

            // 如果当前线程被中断，破坏屏障并抛出异常
            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

            // 计数减一，表示一个线程已经到达屏障
            int index = --count;
            // 如果计数为0，表示所有线程都已到达屏障
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    // 获取并执行屏障命令，如果有的话
                    final Runnable command = barrierCommand;
                    if (command != null)
                        command.run();
                    ranAction = true;
                    // 进入下一代，重置屏障状态
                    nextGeneration();
                    return 0;
                } finally {
                    // 如果没有成功执行命令，破坏屏障
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // 循环等待，直到屏障被触发、破坏、当前线程被中断或定时等待结束
            for (;;) {
                try {
                    // 根据timed参数决定使用哪种等待方式
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    // 如果当前代未变且屏障未被破坏，中断屏障并抛出异常
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // 如果即将结束等待，将中断视为属于后续执行
                        Thread.currentThread().interrupt();
                    }
                }

                // 如果屏障被破坏，抛出异常
                if (g.broken)
                    throw new BrokenBarrierException();

                // 如果代已改变，返回当前线程的索引
                if (g != generation)
                    return index;

                // 如果使用定时等待且时间已到，破坏屏障并抛出异常
                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            // 释放锁
            lock.unlock();
        }
    }




    private void nextGeneration() {
        trip.signalAll();
        count = parties;
        generation = new Generation();
    }

    private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }


    public int getParties() {
        return parties;
    }

    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe);
        }
    }

    public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }


    public boolean isBroken() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return generation.broken;
        } finally {
            lock.unlock();
        }
    }


    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();
            nextGeneration();
        } finally {
            lock.unlock();
        }
    }

    public int getNumberWaiting() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return parties - count;
        } finally {
            lock.unlock();
        }
    }
}
